package www.floatwindow.com.floatwindowdemo;

import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.alibaba.idst.nls.NlsClient;
import com.alibaba.idst.nls.NlsListener;
import com.alibaba.idst.nls.StageListener;
import com.alibaba.idst.nls.internal.protocol.NlsRequest;

import www.floatwindow.com.floatwindowdemo.view.AudioRecorderButton;

public class MainActivity extends AppCompatActivity {
    private Handler mHandler = null;

    private NlsClient mNlsClient;
    private NlsRequest mNlsRequest;
    private WindowUtils windowUtils;

    private AlivoiceUtils alivoiceUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        // 获取handler
        mHandler = new Handler();

        // 初始化阿里语音
        alivoiceUtils = new AlivoiceUtils(this);
        // 初始化阿里语音请求
        mNlsRequest = alivoiceUtils.initNlsRequest();

        mNlsRequest.setApp_key(AlivoiceUtils.NLS_SERVICE_MULTI_DOMAIN);
        // 设置语音格式
        mNlsRequest.setAsr_sc("opu");
        // 热词参数
        //mNlsRequest.setAsrVocabularyId("vocabid");
        NlsClient.openLog(true);
        // 全局配置
        NlsClient.configure(getApplicationContext());

        mNlsClient = NlsClient.newInstance(this, mRecognizeListener, mStageListener, mNlsRequest);
        // 设置最长语音
        mNlsClient.setMaxRecordTime(60000);
        // 设置最短语音
        mNlsClient.setMaxStallTime(1000);
        // 设置最大录音中断时间
        mNlsClient.setMinRecordTime(500);
        // 设置VAD
        mNlsClient.setRecordAutoStop(false);
        // 设置音量回调时长
        mNlsClient.setMinVoiceValueInterval(200);

        windowUtils = new WindowUtils(mNlsClient, mNlsRequest);


        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                windowUtils.showPopupWindow(MainActivity.this);
            }
        }, 1000);

        Button button = (Button) findViewById(R.id.btn_show);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "按钮被点击", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showWindow() {
        // 参数设置
        WindowManager.LayoutParams params = new WindowManager.LayoutParams();

        // 类型
        params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;

        // 设置flag
        int flags = WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM;

        // | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        // 如果设置了WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE，弹出的View收不到Back键的事件
        // FLAG_NOT_TOUCH_MODAL不阻塞事件传递到后面的窗口
        // 设置 FLAG_NOT_FOCUSABLE 悬浮窗口较小时，后面的应用图标由不可长按变为可长按
        // 不设置这个flag的话，home页的划屏会有问题
        params.flags = flags;

        // 不设置这个弹出框的透明遮罩显示为黑色
        params.format = PixelFormat.TRANSLUCENT;

        // 设置弹出窗口的宽
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        // 设置弹出窗口的高
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
        // 设置窗口内容的位置
        params.gravity = Gravity.CENTER;

        // 获取内容布局
        final View popupWindowView = View.inflate(this, R.layout.floatwindow, null);

        // 获取内容控件
        AudioRecorderButton btn_add = popupWindowView.findViewById(R.id.id_recorder_button);

        // 点击窗口外部区域可消除
        // 这点的实现主要将悬浮窗设置为全屏大小，外层有个透明背景，中间一部分视为内容区域
        // 所以点击内容区域外部视为点击悬浮窗外部
        btn_add.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                int x = (int) motionEvent.getX();
                int y = (int) motionEvent.getY();
                Rect rect = new Rect();
                popupWindowView.getGlobalVisibleRect(rect);
                if (!rect.contains(x, y)) {
                    windowUtils.hideBtnPopupWindow();
                }

                Toast.makeText(MainActivity.this, "正在说话", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
    }

    private NlsListener mRecognizeListener = new NlsListener() {
        @Override
        public void onRecognizingResult(int status, RecognizedResult result) {
            Toast.makeText(MainActivity.this, status + "", Toast.LENGTH_LONG).show();
            switch (status) {
                case NlsClient.ErrorCode.SUCCESS:
//                    mResultEdit.setText(result.asr_out);
//                    mFullEdit.setText(result.asr_out);
                    Toast.makeText(MainActivity.this, result.results, Toast.LENGTH_LONG).show();
                    break;
                case NlsClient.ErrorCode.RECOGNIZE_ERROR:
                    Toast.makeText(MainActivity.this, "recognizer error", Toast.LENGTH_LONG).show();
                    break;
                case NlsClient.ErrorCode.RECORDING_ERROR:
                    Toast.makeText(MainActivity.this, "recording error", Toast.LENGTH_LONG).show();
                    break;
                case NlsClient.ErrorCode.NOTHING:
                    Toast.makeText(MainActivity.this, "nothing", Toast.LENGTH_LONG).show();
                    break;
                default:
                    break;
            }
        }
    };


    private StageListener mStageListener = new StageListener() {
        @Override
        public void onStartRecognizing(NlsClient recognizer) {
            super.onStartRecognizing(recognizer);    //To change body of overridden methods use File | Settings | File Templates.
        }

        @Override
        public void onStopRecognizing(NlsClient recognizer) {
            super.onStopRecognizing(recognizer);    //To change body of overridden methods use File | Settings | File Templates.
        }

        @Override
        public void onStartRecording(NlsClient recognizer) {
            super.onStartRecording(recognizer);    //To change body of overridden methods use File | Settings | File Templates.
        }

        @Override
        public void onStopRecording(NlsClient recognizer) {
            super.onStopRecording(recognizer);    //To change body of overridden methods use File | Settings | File Templates.
        }

        @Override
        public void onVoiceVolume(int volume) {
            super.onVoiceVolume(volume);
        }
    };
}
